﻿using System;
using System.IO;
using System.Text;
using System.Web;

namespace submerged
{
    public partial class _Default : System.Web.UI.Page
    {
        private bool IsNumber(string strNumber)
        {
            for (int i = 0; i < strNumber.Length; i++)
            {
                if (!Char.IsNumber(strNumber[i]))
                {
                    return false;
                }
            }
            return true;
        }

        private bool validarIngreso() {
            if (Request.HttpMethod == "POST")
            {

                if (Request.Files[0] != null && Request.Files[1] != null)
                {
                    if (Request.Files[0].ContentLength < 500000 && Request.Files[1].ContentLength < 500000)
                    {
                        if (Request.Files[0].FileName != "" && Request.Files[1].FileName != "")
                        {
                            if (!string.IsNullOrEmpty(Request.Form["separacion"]))
                            {
                                if (IsNumber(Request.Form["separacion"].Replace(".","")))
                                {
                                    return true;
                                }
                            }
                            else {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }

        private StringBuilder procesarArch1(Stream arch1, out LineaSub lns)
        {
            StreamReader reader = new StreamReader(arch1, Encoding.GetEncoding("iso-8859-1"));
            StringBuilder mergeSub = new StringBuilder();
            lns = new LineaSub();
            string linea;
            while (!reader.EndOfStream)
            {
                linea = reader.ReadLine();
                if (linea != "")
                {
                    if (IsNumber(linea))
                    {
                        lns.nroLinea = Convert.ToInt32(linea);
                    }
                    else
                    {
                        if (linea.Contains("-->"))
                        {
                            string desde = linea.Split("-->".ToCharArray())[0];
                            string hasta = linea.Split("-->".ToCharArray())[linea.Split("-->".ToCharArray()).Length - 1];

                            TimeSpan ts1 = new TimeSpan();
                            TimeSpan.TryParse(desde.Replace(',', '.'), out ts1);
                            lns.desde = ts1;

                            TimeSpan ts2 = new TimeSpan();
                            TimeSpan.TryParse(hasta.Replace(',', '.'), out ts2);
                            lns.hasta = ts2;

                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(lns.texto))
                            {
                                lns.texto += "\r\n";
                            }
                            lns.texto += linea;
                        }
                    }
                    
                }
                else {
                    lns = new LineaSub();
                }
                mergeSub.AppendLine(linea);

            }
            return mergeSub;
        }
        private StringBuilder procesarArch2(Stream arch2, StringBuilder arch1Str,LineaSub ultimaLinea1) {
            TimeSpan offset ;
            string strOffset=Request.Form["separacion"];
            if (strOffset.Contains("."))
            {
                int segs = Convert.ToInt32(strOffset.Split('.')[0]);
                int msegs = Convert.ToInt32(strOffset.Split('.')[strOffset.Split('.').Length-1]);
                offset = new TimeSpan(0, 0, 0, segs, msegs);
            }
            else {
                offset = new TimeSpan(0, 0,Convert.ToInt32( strOffset));
            }

            StreamReader reader = new StreamReader(arch2, Encoding.GetEncoding("iso-8859-1"));
            LineaSub lns = new LineaSub();
            string linea;
            arch1Str.AppendLine("");
            while (!reader.EndOfStream)
            {
                linea = reader.ReadLine();
                if (linea != "")
                {
                    if (IsNumber(linea))
                    {
                        lns.nroLinea = Convert.ToInt32(linea);
                        linea = (lns.nroLinea + ultimaLinea1.nroLinea).ToString();
                    }
                    else
                    {
                        if (linea.Contains("-->"))
                        {
                            string desde = linea.Split("-->".ToCharArray())[0];
                            string hasta = linea.Split("-->".ToCharArray())[linea.Split("-->".ToCharArray()).Length - 1];

                            TimeSpan ts1 = new TimeSpan();
                            TimeSpan.TryParse(desde.Replace(',', '.'), out ts1);
                            lns.desde = ts1;

                            TimeSpan ts2 = new TimeSpan();
                            TimeSpan.TryParse(hasta.Replace(',', '.'), out ts2);
                            lns.hasta = ts2;

                            //01:14:16,160 --> 01:14:17,275
                            lns.desde = lns.desde + ultimaLinea1.hasta+offset;
                            string strDesde = string.Format("{0:00}:{1:00}:{2:00},{3:000}", lns.desde.Hours, lns.desde.Minutes, lns.desde.Seconds, lns.desde.Milliseconds);

                            lns.hasta = lns.hasta + ultimaLinea1.hasta+offset;
                            string strHasta = string.Format("{0:00}:{1:00}:{2:00},{3:000}", lns.hasta.Hours, lns.hasta.Minutes, lns.hasta.Seconds, lns.hasta.Milliseconds);

                            linea = strDesde;
                            linea += " --> ";
                            linea += strHasta;

                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(lns.texto))
                            {
                                lns.texto += "\r\n";
                            }
                            lns.texto += linea;
                        }
                    }

                }
                else
                {
                    lns = new LineaSub();
                }
                arch1Str.AppendLine(linea);

            }
            return arch1Str;
        }
        private void EnviarRespuesta(StringBuilder response) {
            Response.Clear();
            Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Request.Files[0].FileName.Replace("1", "")));
            Response.Charset = "iso-8859-1";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.text";
            Response.Write(response.ToString());

            Response.End();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (validarIngreso()) {
                LineaSub lns = new LineaSub();

                StringBuilder mergeSub = procesarArch1(Request.Files[0].InputStream, out lns);
                mergeSub= procesarArch2(Request.Files[1].InputStream, mergeSub, lns);
                

                EnviarRespuesta(mergeSub);
            }
        }
    }
            
}
            
           
